<template>
  <div>
    <a-page-header
        style="border: 1px solid rgb(235, 237, 240)"
        title="题库管理"
        sub-title="新增、修改、删除题目"
        @back="() => $router.go(-1)"
    >
      <template slot="extra">
        <a-input-search key="1" v-model="search.key" placeholder="请输入关键词" style="width: 200px" @search="loadData" />
        <a-button key="2" type="primary" icon="plus" @click="onOpenAdd">
          新增题目
        </a-button>
      </template>
      <a-row type="flex">
        <a-statistic title="题目总量" suffix="道" :value="count.all" style="margin: 0 32px;"/>
        <a-statistic title="判断题" suffix="道" :value="count.judge" style="margin: 0 32px;"/>
        <a-statistic title="单选题" suffix="道" :value="count.radio" style="margin: 0 32px;"/>
        <a-statistic title="多选题" suffix="道" :value="count.multiple" style="margin: 0 32px;"/>
        <a-statistic title="填空题" suffix="道" :value="count.fill" style="margin: 0 32px;"/>
      </a-row>
      <template slot="footer">
        <a-table
            :columns="columns"
            :scroll="{ x: 1000 }"
            size="middle"
            :pagination="false"
            :dataSource="dataSource"
            :loading="loading"
        >
          <span slot="title" slot-scope="title">
            <a-tag :color="type.color" v-for="(type, index) in title.types" v-bind:key="index">{{type.text}}</a-tag>{{title.title}}
          </span>
          <span slot="answer" slot-scope="answers">
            <a-tag :color="answer.color" v-for="(answer, index) in answers" v-bind:key="index">{{answer.text}}</a-tag>
          </span>
          <span slot="action" slot-scope="record">
            <a @click="onOpenEdit(record)">修改</a>
            <a-divider type="vertical"/>
            <a style="color: #eb1c25" @click="onDelQuestion(record.id)">删除</a>
          </span>
        </a-table>
        <br>
        <a-config-provider :locale="zhCN">
          <a-pagination size="small" :total="total" show-size-changer show-quick-jumper :pageSizeOptions="['10', '30', '50', '100']" @change="changePage" @showSizeChange="changeSize"/>
        </a-config-provider>
        <br>
      </template>
    </a-page-header>
    <a-modal :title="currentQuestion === null ? '添加新题':'修改题目'" :width="600" :visible="showAdd" :ok-text="currentQuestion === null ? '添加':'修改'" cancel-text="取消" @ok="onSubmitQuestion" @cancel="onCloseAdd" :ok-button-props="{ props: { disabled: !enableAdd , loading: btnAddLoading} }">
      <a-form-model ref="ruleForm" :model="formData">
        <a-form-model-item required label="题目">
          <a-input type="textarea" v-model="formData.title" placeholder="请输入题目(500字以内)"/>
        </a-form-model-item>
        <a-form-model-item required label="类型">
          <a-radio-group button-style="solid" v-model="formData.type" :disabled="currentQuestion !== null">
            <a-radio-button :value="0">
              判断题
            </a-radio-button>
            <a-radio-button :value="1">
              单选题
            </a-radio-button>
            <a-radio-button :value="2">
              多选题
            </a-radio-button>
            <a-radio-button :value="3">
              填空题
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <template v-if="formData.type === 1 || formData.type === 2">
          <a-form-model-item :required="index < 2" :label="'选项' + (index + 1)" v-for="(item, index) in formData.options" v-bind:key="index">
            <a-input type="textarea" v-model="formData.options[index]" :placeholder="'请输入选项' + (index + 1) + '(200字以内)'"/>
          </a-form-model-item>
        </template>
        <a-form-model-item required label="答案" v-if="formData.type === 0">
          <a-switch checked-children="对" un-checked-children="错" default-checked v-model="formData.judgeAnswer"/>
        </a-form-model-item>
        <a-form-model-item required label="答案" v-if="formData.type === 1">
          <a-radio-group button-style="solid" v-model="formData.radioAnswer">
            <a-radio-button :value="0">
              选项1
            </a-radio-button>
            <a-radio-button :value="1">
              选项2
            </a-radio-button>
            <a-radio-button :value="2" :disabled="!formData.options[2]">
              选项3
            </a-radio-button>
            <a-radio-button :value="3" :disabled="!formData.options[3]">
              选项4
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item required label="答案" v-if="formData.type === 2">
          <a-checkbox-group v-model="formData.multipleAnswer" :options="[{ label: '选项1', value: 0 },{ label: '选项2', value: 1 },{ label: '选项3', value: 2, disabled: !formData.options[2] },{ label: '选项4', value: 3, disabled: !formData.options[3] },]"/>
        </a-form-model-item>
        <a-form-model-item required :label="'答案' + (formData.fillRegular?'(正则)':'')" v-if="formData.type === 3">
          <a-input type="textarea" v-model="formData.fillAnswer" :placeholder="'请输入' + (formData.fillRegular?'正则表达式':'答案') + '(100字以内)'"/>
        </a-form-model-item>
        <a-form-model-item required label="启用正则表达式" v-if="formData.type === 3">
          <a-switch v-model="formData.fillRegular"/>
        </a-form-model-item>
        <a-form-model-item required label="区分大小写" v-if="formData.type === 3">
          <a-switch v-model="formData.fillCase"/>
        </a-form-model-item>
      </a-form-model>
      <a v-if="formData.type === 3 && formData.fillRegular && formData.fillAnswer.length > 0" @click="()=>{showTest = true}">正则测试</a>
    </a-modal>


    <a-modal title="正则测试" :width="600" :visible="showTest" ok-text="测试" cancel-text="取消" @ok="onSubmitTest" @cancel="onCloseTest" :ok-button-props="{ props: { disabled: !enableTest , loading: btnTestLoading} }">
      <a-form-model ref="ruleForm" :model="formData">
        <a-form-model-item required label="正则表达式">
          <a-input type="textarea" v-model="formData.fillAnswer" placeholder="请输入正则表达式(100字以内)" @change="()=>{testResult = null}"/>
        </a-form-model-item>
      </a-form-model>
      <a-form-model-item required label="区分大小写" v-if="formData.type === 3">
        <a-switch v-model="formData.fillCase" @change="()=>{testResult = null}"/>
      </a-form-model-item>
      <a-form-model ref="ruleForm" :model="formData">
        <a-form-model-item required label="测试内容">
          <a-input type="textarea" v-model="formData.testText" placeholder="请输入要测试的内容(100字以内)" @change="()=>{testResult = null}"/>
        </a-form-model-item>
      </a-form-model>
      <a-alert v-if="testResult === true" message="匹配成功" type="success" show-icon />
      <a-alert v-if="testResult === false" message="匹配失败" type="error" show-icon />
    </a-modal>

  </div>
</template>

<script>
import global from "@/components/global";
import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    key: "id",
    width: "3em",
    fixed: 'left',
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    width: "10em",
    ellipsis: true,
  },
  {
    title: "创建者",
    dataIndex: "creator",
    key: "creator",
    width: "5em",
    ellipsis: true,
  },
  {
    title: "题目",
    dataIndex: "title",
    key: "title",
    width: "25em",
    ellipsis: true,
    scopedSlots: {customRender: "title"},
  },
  {
    title: "答案",
    dataIndex: "answer",
    key: "answer",
    width: "15em",
    ellipsis: true,
    scopedSlots: {customRender: "answer"},
  },
  {
    title: "选项1",
    dataIndex: "option1",
    key: "option1",
    width: "15em",
    ellipsis: true,
  },
  {
    title: "选项2",
    dataIndex: "option2",
    key: "option2",
    width: "15em",
    ellipsis: true,
  },
  {
    title: "选项3",
    dataIndex: "option3",
    key: "option3",
    width: "15em",
    ellipsis: true,
  },
  {
    title: "选项4",
    dataIndex: "option4",
    key: "option4",
    width: "15em",
    ellipsis: true,
  },
  {
    title: "操作",
    key: "action",
    width: "15em",
    fixed: 'right',
    scopedSlots: {customRender: "action"},
  },
];


export default {
  name: "questions",
  data() {
    return {
      zhCN,
      total: 0,
      search:{
        page: 0,
        size: 10,
        key: ''
      },
      loading: false,
      columns: columns,
      dataSource:[],
      showAdd: false,
      btnAddLoading: false,
      formData:{
        title: '',
        type: 0,
        options: ['', '', '', ''],
        judgeAnswer: true,
        radioAnswer: 0,
        multipleAnswer: [0, 1],
        fillAnswer: '',
        fillCase: false,
        fillRegular: false,
        testText: ''
      },
      currentQuestion: null,
      count: {
        all: 0,
        judge: 0,
        radio: 0,
        multiple: 0,
        fill: 0
      },
      showTest: false,
      btnTestLoading: false,
      testResult: null
    }
  },
  methods:{
    onSubmitTest(){
      let that = this
      that.btnTestLoading = true
      global.http(this, 'api/Question/RegularTest', {
        data: {
          regularExpression: that.formData.fillAnswer,
          testText: that.formData.testText,
          case: that.formData.fillCase
        },
        successText: '',
        failText: '',
        success(res){
          that.testResult = res.data.result
        },
        complete() {
          that.btnTestLoading = false
        },
      })
    },
    onOpenAdd(){
      this.formData = {
        title: '',
        type: 0,
        options: ['', '', '', ''],
        judgeAnswer: true,
        radioAnswer: 0,
        multipleAnswer: [0, 1],
        fillAnswer: '',
        fillCase: false,
        fillRegular: false
      }
      this.currentQuestion = null
      this.showAdd = true
    },
    onOpenEdit(q){
      this.currentQuestion = q.source
      this.formData.title = this.currentQuestion.title
      this.formData.type = this.currentQuestion.type
      switch (this.currentQuestion.type){
        case 0:
          this.formData.judgeAnswer = this.currentQuestion.answer==="true"
          break;
        case 1:
          this.formData.radioAnswer = Number(this.currentQuestion.answer)
          break;
        case 2:
          this.formData.multipleAnswer = JSON.parse(this.currentQuestion.answer)
          break;
        case 3:
          this.formData.fillAnswer = this.currentQuestion.answer
          this.formData.fillRegular = this.currentQuestion.option1 === 'true'
          this.formData.fillCase = this.currentQuestion.option2 === 'true'
          break;
        default:
          break;
      }
      if(this.currentQuestion.type === 1 || this.currentQuestion.type === 2){
        this.formData.options = [this.currentQuestion.option1, this.currentQuestion.option2, this.currentQuestion.option3, this.currentQuestion.option4]
      }
      this.showAdd = true
    },
    onDelQuestion(id){
      let that = this
      this.$confirm({
        title: '提示',
        content: '确定要删除吗?',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          global.http(that, 'api/Question/Delete?id=' + id, {
            successText: '删除成功',
            failText: '删除失败',
            success(){
              that.loadData()
            }
          })
        },
      });
    },
    onSubmitQuestion(){
      let that = this
      let postData = {
        title: that.formData.title,
        type: that.formData.type,
      }
      switch (this.formData.type){
        case 0:
          postData.answer = this.formData.judgeAnswer?'true':'false'
          break;
        case 1:
        case 2:
          this.formData.type === 1 && (postData.answer = this.formData.radioAnswer.toString())
          this.formData.type === 2 && (postData.answer = JSON.stringify(this.formData.multipleAnswer))
          postData.option1 = this.formData.options[0]
          postData.option2 = this.formData.options[1]
          this.formData.options[2] && (postData.option3 = this.formData.options[2])
          this.formData.options[3] && (postData.option4 = this.formData.options[3])
          break;
        case 3:
          postData.answer = this.formData.fillAnswer
          postData.option1 = this.formData.fillRegular?'true':'false'
          postData.option2 = this.formData.fillCase?'true':'false'
          break;
        default:
          break;
      }
      that.btnAddLoading = true
      if(this.currentQuestion === null){
        global.http(this, 'api/Question/Add', {
          data: postData,
          successText: '添加成功',
          failText: '添加失败',
          success(){
            that.showAdd = false
            that.loadData()
          },
          complete(){
            that.btnAddLoading = false
          }
        })
      }else {
        postData.id = that.currentQuestion.id
        global.http(this, 'api/Question/Update', {
          data: postData,
          successText: '修改成功',
          failText: '修改失败',
          success(){
            that.showAdd = false
            that.currentQuestion = null
            that.loadData()
          },
          complete(){
            that.btnAddLoading = false
          }
        })
      }
    },
    onCloseAdd(){
      this.showAdd = false
    },
    onCloseTest(){
      this.showTest = false
    },
    changeSize(page, size){
      this.search.page = page - 1
      this.search.size = size
      this.loadData()
    },
    changePage(page, size){
      this.search.page = page - 1
      this.search.size = size
      this.loadData()
    },
    loadData(){
      let that = this
      that.loading = true
      global.http(this, 'api/Question/Search', {
        data: that.search,
        success(res){
          that.dataSource = res.data.questions.map(x=>{
            x.source = JSON.parse(JSON.stringify(x))
            x.key = x.id
            x.createTime = global.dateToYmdHm(x.createTime)
            switch (x.type){
              case 0:
                x.answer = [{color: x.answer==='true'?'green':'red', text: x.answer==='true'?'正确':'错误'}]
                break;
              case 1:
                x.answer = [{color: 'pink', text: '选项' + (Number(x.answer) + 1)}]
                break;
              case 2:
                x.answer = JSON.parse(x.answer).map(y=>{
                  return {color: 'blue', text: '选项' + (y + 1)}
                })
                break;
              case 3:
                x.answer = [{color: '', text: x.answer}]
                break;
              default:
                break;
            }
            if(x.type === 3){
              x.type = [{color: ['orange', 'pink', 'blue', 'cyan'][x.type], text: ['判断题', '单选题', '多选题', '填空题'][x.type]}]
              x.option1==='true' && x.type.push({color: 'purple', text: '正则'})
              x.option2==='true' && x.type.push({color: 'gold', text: '区分大小写'})
              x.option1 = ''
              x.option2 = ''
            }else {
              x.type = [{color: ['orange', 'pink', 'blue', 'cyan'][x.type], text: ['判断题', '单选题', '多选题', '填空题'][x.type]}]
            }
            x.title = {title: x.title, types: x.type}
            return x
          })
          that.count.all = res.data.all
          that.count.judge = res.data.judge
          that.count.radio = res.data.radio
          that.count.multiple = res.data.multiple
          that.count.fill = res.data.fill
          that.total = res.data.total
        },
        complete(){
          that.loading = false
        }
      })
    }
  },
  computed: {
    enableAdd(){
      let result = global.strLenLimit(this.formData.title, 500, )
      switch (this.formData.type){
        case 1:
        case 2:
          result = result && global.strLenLimit(this.formData.options[0], 100)
          result = result && global.strLenLimit(this.formData.options[1], 100)
          if(global.strLenLimit(this.formData.options[3], 100)){
            result = result && global.strLenLimit(this.formData.options[2], 100)
          }
          if(this.formData.type === 2){
            result = result && this.formData.multipleAnswer.length > 1
          }
          break;
        case 3:
          result = result && global.strLenLimit(this.formData.fillAnswer, 100)
          break;
        default:
          break;
      }
      return result
    },
    enableTest(){
      return global.strLenLimit(this.formData.fillAnswer, 100) && global.strLenLimit(this.formData.testText, 100)
    }
  },
  mounted() {
    this.loadData()
  }
}
</script>

<style scoped>

</style>